package com.initialize.common.tool.sms.util;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSONException;
import com.aliyun.oss.ClientException;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.initialize.common.tool.sms.config.SMSAConfig;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: star-blockchain
 * @description: 阿里云短信服务
 * @author: Mr.Jane
 * @create: 2019-09-28 16:31
 **/
@Component
public class SmsAService {


    /**
     * 发送短信给用户
     * @param phoneNumber 用户的手机号
     * @param param 随机数字
     * @param TemplateCode 模板id
     * @return
     */
    public boolean smsToUser(String phoneNumber, String param, String TemplateCode) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", SMSAConfig.ACCESSKEY, SMSAConfig.SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        Map<String, Object> codemap = new LinkedHashMap<String, Object>();
        if (!param.equals("1")) {
            codemap.put("code", param);
        }
        JSONObject jsonObject = new JSONObject(codemap);
        String codeJson = jsonObject.toString();
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", "star");
        request.putQueryParameter("TemplateCode", TemplateCode);
        request.putQueryParameter("TemplateParam", codeJson);
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            System.out.println(data);
            String string = new JSONObject(data).get("Code").toString();
            if (string.equals("OK")) {
                return true;
            }

        } catch (ClientException | com.aliyuncs.exceptions.ClientException | JSONException e) {
            e.printStackTrace();
        }

        return false;
    }

}
